extends Node
class_name DataManager

const CultivationTechnique = preload("res://scripts/cultivation/cultivation_technique.gd")
const Enemy = preload("res://scripts/character/enemy.gd")
const Item = preload("res://scripts/items/item.gd")
const Skill = preload("res://scripts/battle/skill.gd")

# 数据路径
const ITEMS_PATH = "res://data/items.json"
const SKILLS_PATH = "res://data/skills.json"
const TECHNIQUES_PATH = "res://data/techniques.json"
const ENEMIES_PATH = "res://data/enemies.json"
const STORY_PATH = "res://data/story.json"

# 数据缓存
var items_data: Dictionary = {}
var skills_data: Dictionary = {}
var techniques_data: Dictionary = {}
var enemies_data: Dictionary = {}
var story_data: Dictionary = {}

# 信号
signal data_loaded()

# 初始化数据管理器
func _init() -> void:
	# 创建数据目录
	_ensure_data_directory()
	
	# 加载所有数据
	load_all_data()

# 确保数据目录存在
func _ensure_data_directory() -> void:
	var dir = DirAccess.open("res://")
	if not dir.dir_exists("data"):
		dir.make_dir("data")

# 加载所有数据
func load_all_data() -> void:
	load_items()
	load_skills()
	load_techniques()
	load_enemies()
	load_story()
	
	emit_signal("data_loaded")

# 加载物品数据
func load_items() -> void:
	items_data = _load_json_file(ITEMS_PATH)
	
	# 如果文件不存在或为空，创建默认数据
	if items_data.is_empty():
		_create_default_items()
		save_items()

# 加载技能数据
func load_skills() -> void:
	skills_data = _load_json_file(SKILLS_PATH)
	
	# 如果文件不存在或为空，创建默认数据
	if skills_data.is_empty():
		_create_default_skills()
		save_skills()

# 加载功法数据
func load_techniques() -> void:
	techniques_data = _load_json_file(TECHNIQUES_PATH)
	
	# 如果文件不存在或为空，创建默认数据
	if techniques_data.is_empty():
		_create_default_techniques()
		save_techniques()

# 加载敌人数据
func load_enemies() -> void:
	enemies_data = _load_json_file(ENEMIES_PATH)
	
	# 如果文件不存在或为空，创建默认数据
	if enemies_data.is_empty():
		_create_default_enemies()
		save_enemies()

# 加载剧情数据
func load_story() -> void:
	story_data = _load_json_file(STORY_PATH)
	
	# 如果文件不存在或为空，创建默认数据
	if story_data.is_empty():
		_create_default_story()
		save_story()
	

# 保存物品数据
func save_items() -> void:
	_save_json_file(ITEMS_PATH, items_data)

# 保存技能数据
func save_skills() -> void:
	_save_json_file(SKILLS_PATH, skills_data)

# 保存功法数据
func save_techniques() -> void:
	_save_json_file(TECHNIQUES_PATH, techniques_data)

# 保存敌人数据
func save_enemies() -> void:
	_save_json_file(ENEMIES_PATH, enemies_data)

# 保存剧情数据
func save_story() -> void:
	_save_json_file(STORY_PATH, story_data)

# 从JSON文件加载数据
func _load_json_file(file_path: String) -> Dictionary:
	if not FileAccess.file_exists(file_path):
		return {}
	
	var file = FileAccess.open(file_path, FileAccess.READ)
	if not file:
		return {}
	
	var json_string = file.get_as_text()
	file.close()
	
	var json = JSON.new()
	var error = json.parse(json_string)
	
	if error == OK:
		return json.data
	else:
		print("JSON解析错误: ", json.get_error_message(), " 在行 ", json.get_error_line())
		return {}

# 保存数据到JSON文件
func _save_json_file(file_path: String, data: Dictionary) -> void:
	var file = FileAccess.open(file_path, FileAccess.WRITE)
	if not file:
		return
	
	file.store_string(JSON.stringify(data, "  "))
	file.close()

# 创建物品实例
func create_item(item_id: String) -> Item:
	if not items_data.has(item_id):
		return null
	
	var item_data = items_data[item_id]
	var item = Item.new()
	
	# 设置基本属性
	item.item_name = item_data.name
	item.description = item_data.description
	item.item_type = item_data.item_type
	item.quality = item_data.quality
	item.value = item_data.value
	item.max_stack = item_data.max_stack
	item.stack_size = 1
	
	# 设置装备属性
	if item_data.has("can_equip"):
		item.can_equip = item_data.can_equip
		
		if item.can_equip:
			item.equip_slot = item_data.equip_slot
			item.health_bonus = item_data.health_bonus
			item.spirit_bonus = item_data.spirit_bonus
			item.attack_bonus = item_data.attack_bonus
			item.defense_bonus = item_data.defense_bonus
			item.speed_bonus = item_data.speed_bonus
	
	# 设置消耗品属性
	if item_data.has("health_restore"):
		item.health_restore = item_data.health_restore
	
	if item_data.has("spirit_restore"):
		item.spirit_restore = item_data.spirit_restore
	
	if item_data.has("effect_duration"):
		item.effect_duration = item_data.effect_duration
	
	return item

# 创建技能实例
func create_skill(skill_id: String) -> Skill:
	if not skills_data.has(skill_id):
		return null
	
	var skill_data = skills_data[skill_id]
	var skill = Skill.new()
	
	# 设置基本属性
	skill.skill_name = skill_data.name
	skill.description = skill_data.description
	skill.skill_type = skill_data.skill_type
	skill.spirit_cost = skill_data.spirit_cost
	skill.cooldown = skill_data.cooldown
	skill.base_power = skill_data.base_power
	skill.scaling_stat = skill_data.scaling_stat
	skill.scaling_factor = skill_data.scaling_factor
	
	# 设置元素属性（如果有）
	if skill_data.has("element"):
		skill.set_meta("element", skill_data.element)
	
	# 设置状态效果（如果有）
	if skill_data.has("status_effect") and skill_data.has("status_chance"):
		skill.set_meta("status_effect", skill_data.status_effect)
		skill.set_meta("status_chance", skill_data.status_chance)
	
	# 设置目标类型（如果有）
	if skill_data.has("targets"):
		skill.set_meta("targets", skill_data.targets)
	
	return skill

# 创建功法实例
func create_technique(technique_id: String) -> CultivationTechnique:
	if not techniques_data.has(technique_id):
		return null
	
	var technique_data = techniques_data[technique_id]
	var technique = CultivationTechnique.new()
	
	# 设置基本属性
	technique.technique_name = technique_data.name
	technique.description = technique_data.description
	technique.technique_type = technique_data.technique_type
	technique.cultivation_speed_bonus = technique_data.cultivation_speed_bonus
	technique.spirit_recovery_bonus = technique_data.spirit_recovery_bonus
	technique.breakthrough_bonus = technique_data.breakthrough_bonus
	technique.level = technique_data.level
	technique.max_level = technique_data.max_level
	technique.element_affinity = technique_data.element_affinity
	technique.required_realm = technique_data.required_realm
	technique.required_spirit_root = technique_data.required_spirit_root
	# 将special_effects从普通Array转换为Array[String]类型
	technique.special_effects.clear()
	for effect in technique_data.special_effects:
		technique.special_effects.append(effect)
	technique.attack_bonus = technique_data.attack_bonus
	technique.defense_bonus = technique_data.defense_bonus
	technique.speed_bonus = technique_data.speed_bonus
	
	return technique

# 创建敌人实例
func create_enemy(enemy_id: String, level: int = 1) -> Enemy:
	if not enemies_data.has(enemy_id):
		return null
	
	var enemy_data = enemies_data[enemy_id]
	var enemy = Enemy.new(enemy_data.name, level)
	
	# 设置基本属性
	enemy.enemy_type = enemy_data.enemy_type
	
	# 根据等级调整属性
	enemy._scale_stats_by_level()
	
	# 添加技能
	if enemy_data.has("skills"):
		for skill_id in enemy_data.skills:
			var skill = create_skill(skill_id)
			if skill:
				enemy.add_skill(skill)
	
	# 设置掉落
	if enemy_data.has("drops"):
		for drop in enemy_data.drops:
			var item = create_item(drop.item_id)
			if item:
				enemy.add_drop(item, drop.chance)
	
	# 设置灵石掉落
	if enemy_data.has("spirit_stone_drop"):
		enemy.set_spirit_stone_drop(
			enemy_data.spirit_stone_drop.min,
			enemy_data.spirit_stone_drop.max
		)
	
	# 设置AI行为
	if enemy_data.has("ai_behavior"):
		enemy.ai_behavior = enemy_data.ai_behavior
	
	return enemy

# 获取物品列表
func get_items_list() -> Array:
	var items = []
	for item_id in items_data.keys():
		items.append({
			"id": item_id,
			"name": items_data[item_id].name,
			"type": items_data[item_id].item_type,
			"quality": items_data[item_id].quality
		})
	return items

# 获取技能列表
func get_skills_list() -> Array:
	var skills = []
	for skill_id in skills_data.keys():
		skills.append({
			"id": skill_id,
			"name": skills_data[skill_id].name,
			"type": skills_data[skill_id].skill_type
		})
	return skills

# 获取功法列表
func get_techniques_list() -> Array:
	var techniques = []
	for technique_id in techniques_data.keys():
		techniques.append({
			"id": technique_id,
			"name": techniques_data[technique_id].name,
			"type": techniques_data[technique_id].technique_type,
			"required_realm": techniques_data[technique_id].required_realm
		})
	return techniques

# 获取敌人列表
func get_enemies_list() -> Array:
	var enemies = []
	for enemy_id in enemies_data.keys():
		enemies.append({
			"id": enemy_id,
			"name": enemies_data[enemy_id].name,
			"type": enemies_data[enemy_id].enemy_type
		})
	return enemies

# 创建默认物品数据
func _create_default_items() -> void:
	items_data = {
		"health_potion_small": {
			"name": "小型回气丹",
			"description": "恢复少量生命值的丹药。",
			"item_type": Item.ItemType.CONSUMABLE,
			"quality": Item.ItemQuality.COMMON,
			"value": 10,
			"max_stack": 10,
			"health_restore": 20,
			"spirit_restore": 0,
			"effect_duration": 0
		},
		"spirit_potion_small": {
			"name": "小型聚灵丹",
			"description": "恢复少量真气的丹药。",
			"item_type": Item.ItemType.CONSUMABLE,
			"quality": Item.ItemQuality.COMMON,
			"value": 15,
			"max_stack": 10,
			"health_restore": 0,
			"spirit_restore": 15,
			"effect_duration": 0
		},
		"basic_sword": {
			"name": "练气剑",
			"description": "一把适合练气期修士使用的法剑。",
			"item_type": Item.ItemType.WEAPON,
			"quality": Item.ItemQuality.COMMON,
			"value": 50,
			"max_stack": 1,
			"can_equip": true,
			"equip_slot": Item.EquipSlot.WEAPON,
			"health_bonus": 0,
			"spirit_bonus": 5,
			"attack_bonus": 10,
			"defense_bonus": 0,
			"speed_bonus": 0
		},
		"basic_robe": {
			"name": "练气袍",
			"description": "一件适合练气期修士穿着的法袍。",
			"item_type": Item.ItemType.ARMOR,
			"quality": Item.ItemQuality.COMMON,
			"value": 40,
			"max_stack": 1,
			"can_equip": true,
			"equip_slot": Item.EquipSlot.BODY,
			"health_bonus": 15,
			"spirit_bonus": 10,
			"attack_bonus": 0,
			"defense_bonus": 5,
			"speed_bonus": 0
		},
		"spirit_stone": {
			"name": "下品灵石",
			"description": "蕴含少量灵气的石头，是修仙界的通用货币。",
			"item_type": Item.ItemType.SPIRIT_STONE,
			"quality": Item.ItemQuality.COMMON,
			"value": 1,
			"max_stack": 99
		},
		"spirit_herb_common": {
			"name": "凡级灵草",
			"description": "一种常见的灵草，可用于炼丹或直接服用恢复生命。",
			"item_type": Item.ItemType.SPIRIT_HERB,
			"quality": Item.ItemQuality.COMMON,
			"value": 5,
			"max_stack": 20,
			"health_restore": 10,
			"spirit_restore": 5,
			"effect_duration": 0
		}
	}

# 创建默认技能数据
func _create_default_skills() -> void:
	skills_data = {
		"basic_attack": {
			"name": "灵气剑",
			"description": "凝聚灵气于剑尖，对敌人造成伤害。",
			"skill_type": Skill.SkillType.ATTACK,
			"spirit_cost": 5,
			"cooldown": 0,
			"base_power": 15,
			"scaling_stat": "attack",
			"scaling_factor": 1.0
		},
		"healing_light": {
			"name": "回春术",
			"description": "运转灵气，恢复自身伤势。",
			"skill_type": Skill.SkillType.HEAL,
			"spirit_cost": 15,
			"cooldown": 2,
			"base_power": 25,
			"scaling_stat": "spirit",
			"scaling_factor": 0.8
		},
		"fire_palm": {
			"name": "烈焰掌",
			"description": "掌心凝聚火属性灵气，对敌人造成火属性伤害并有几率造成灼烧效果。",
			"skill_type": Skill.SkillType.ATTACK,
			"spirit_cost": 20,
			"cooldown": 3,
			"base_power": 35,
			"scaling_stat": "attack",
			"scaling_factor": 1.2,
			"element": "fire",
			"status_effect": "burn",
			"status_chance": 0.3
		},
		"spirit_shield": {
			"name": "灵气护盾",
			"description": "在体表形成灵气护盾，减少受到的伤害。",
			"skill_type": Skill.SkillType.BUFF,
			"spirit_cost": 25,
			"cooldown": 4,
			"base_power": 40,
			"scaling_stat": "defense",
			"scaling_factor": 1.5,
			"duration": 3
		},
		"thunder_strike": {
			"name": "雷霆一击",
			"description": "引动天雷之力，对敌人造成强大的雷属性伤害。",
			"skill_type": Skill.SkillType.ATTACK,
			"spirit_cost": 35,
			"cooldown": 5,
			"base_power": 60,
			"scaling_stat": "attack",
			"scaling_factor": 1.8,
			"element": "thunder",
			"status_effect": "paralysis",
			"status_chance": 0.2
		},
		"five_elements_array": {
			"name": "五行大阵",
			"description": "布下五行相生相克之阵，对所有敌人造成多属性伤害。",
			"skill_type": Skill.SkillType.ATTACK,
			"spirit_cost": 50,
			"cooldown": 8,
			"base_power": 45,
			"scaling_stat": "attack",
			"scaling_factor": 1.5,
			"targets": "all",
			"elements": ["metal", "wood", "water", "fire", "earth"]
		}
	}

# 创建默认功法数据
func _create_default_techniques() -> void:
	techniques_data = {
		"basic_cultivation": {
			"name": "凡体筑基法",
			"description": "最基础的修炼功法，适合初入修仙之路的修士。",
			"technique_type": CultivationTechnique.TechniqueType.FOUNDATION,
			"cultivation_speed_bonus": 1.0,
			"spirit_recovery_bonus": 1.0,
			"breakthrough_bonus": 1.0,
			"level": 1,
			"max_level": 9,
			"element_affinity": "none",
			"required_realm": 0,
			"required_spirit_root": "any",
			"special_effects": [],
			"attack_bonus": 2,
			"defense_bonus": 2,
			"speed_bonus": 2
		},
		"fire_heart_sutra": {
			"name": "烈火心经",
			"description": "以火属性灵气淬炼身心的功法，修炼时会产生灼热感。",
			"technique_type": CultivationTechnique.TechniqueType.ELEMENTAL,
			"cultivation_speed_bonus": 1.2,
			"spirit_recovery_bonus": 0.8,
			"breakthrough_bonus": 1.1,
			"level": 1,
			"max_level": 9,
			"element_affinity": "fire",
			"required_realm": 1,
			"required_spirit_root": "fire",
			"special_effects": ["fire_resistance"],
			"attack_bonus": 5,
			"defense_bonus": 1,
			"speed_bonus": 3
		},
		"jade_body_scripture": {
			"name": "玉体经",
			"description": "注重强化体魄的功法，可以增强修士的防御力。",
			"technique_type": CultivationTechnique.TechniqueType.BODY,
			"cultivation_speed_bonus": 0.9,
			"spirit_recovery_bonus": 1.0,
			"breakthrough_bonus": 1.0,
			"level": 1,
			"max_level": 9,
			"element_affinity": "earth",
			"required_realm": 1,
			"required_spirit_root": "any",
			"special_effects": ["physical_resistance"],
			"attack_bonus": 2,
			"defense_bonus": 8,
			"speed_bonus": 0
		},
		"wind_walker_art": {
			"name": "御风行",
			"description": "讲究轻灵快速的身法功法，可大幅提升修士的速度。",
			"technique_type": CultivationTechnique.TechniqueType.MOVEMENT,
			"cultivation_speed_bonus": 1.0,
			"spirit_recovery_bonus": 1.2,
			"breakthrough_bonus": 1.0,
			"level": 1,
			"max_level": 9,
			"element_affinity": "wind",
			"required_realm": 2,
			"required_spirit_root": "wind",
			"special_effects": ["movement_boost"],
			"attack_bonus": 1,
			"defense_bonus": 1,
			"speed_bonus": 10
		},
		"five_elements_heart_sutra": {
			"name": "五行心经",
			"description": "融会五行之力的高深功法，修炼难度较大但收益颇丰。",
			"technique_type": CultivationTechnique.TechniqueType.ADVANCED,
			"cultivation_speed_bonus": 1.5,
			"spirit_recovery_bonus": 1.3,
			"breakthrough_bonus": 1.4,
			"level": 1,
			"max_level": 9,
			"element_affinity": "all",
			"required_realm": 3,
			"required_spirit_root": "five_elements",
			"special_effects": ["elemental_mastery"],
			"attack_bonus": 6,
			"defense_bonus": 6,
			"speed_bonus": 6
		}
	}

# 创建默认敌人数据
func _create_default_enemies() -> void:
	enemies_data = {
		"training_dummy": {
			"name": "木人桩",
			"enemy_type": Enemy.EnemyType.BEAST,
			"base_health": 50,
			"base_spirit": 0,
			"base_attack": 5,
			"base_defense": 15,
			"base_speed": 0,
			"ai_behavior": Enemy.AIBehavior.DEFENSIVE,
			"skills": [],
			"drops": [
				{"item_id": "spirit_stone", "chance": 1.0}
			],
			"spirit_stone_drop": {"min": 1, "max": 2}
		},
		"wild_beast": {
			"name": "噬灵兽",
			"enemy_type": Enemy.EnemyType.BEAST,
			"base_health": 80,
			"base_spirit": 20,
			"base_attack": 15,
			"base_defense": 8,
			"base_speed": 12,
			"ai_behavior": Enemy.AIBehavior.AGGRESSIVE,
			"skills": ["basic_attack"],
			"drops": [
				{"item_id": "spirit_herb_common", "chance": 0.5},
				{"item_id": "spirit_stone", "chance": 1.0}
			],
			"spirit_stone_drop": {"min": 2, "max": 5}
		},
		"bandit_cultivator": {
			"name": "邪修",
			"enemy_type": Enemy.EnemyType.CULTIVATOR,
			"base_health": 100,
			"base_spirit": 50,
			"base_attack": 18,
			"base_defense": 12,
			"base_speed": 15,
			"ai_behavior": Enemy.AIBehavior.AGGRESSIVE,
			"skills": ["basic_attack", "fire_palm"],
			"drops": [
				{"item_id": "basic_sword", "chance": 0.2},
				{"item_id": "spirit_stone", "chance": 1.0}
			],
			"spirit_stone_drop": {"min": 5, "max": 10}
		},
		"demon_beast": {
			"name": "妖兽",
			"enemy_type": Enemy.EnemyType.DEMON,
			"base_health": 150,
			"base_spirit": 80,
			"base_attack": 25,
			"base_defense": 20,
			"base_speed": 18,
			"ai_behavior": Enemy.AIBehavior.AGGRESSIVE,
			"skills": ["basic_attack", "thunder_strike"],
			"drops": [
				{"item_id": "spirit_herb_common", "chance": 0.8},
				{"item_id": "spirit_stone", "chance": 1.0}
			],
			"spirit_stone_drop": {"min": 8, "max": 15}
		},
		"elder_cultivator": {
			"name": "元婴期修士",
			"enemy_type": Enemy.EnemyType.BOSS,
			"base_health": 300,
			"base_spirit": 200,
			"base_attack": 40,
			"base_defense": 35,
			"base_speed": 30,
			"ai_behavior": Enemy.AIBehavior.STRATEGIC,
			"skills": ["basic_attack", "fire_palm", "thunder_strike", "five_elements_array"],
			"drops": [
				{"item_id": "spirit_stone", "chance": 1.0},
				{"item_id": "basic_sword", "chance": 0.5},
				{"item_id": "basic_robe", "chance": 0.5}
			],
			"spirit_stone_drop": {"min": 20, "max": 50}
		}
	}

# 创建默认剧情数据：
func _create_default_story() -> void:
	story_data = {
		"chapters": {
			"chapter_1": {
				"title": "踏入修仙",
				"description": "你初入修仙世界，开始了漫长的修炼之路。",
				"quests": {
					"quest_1": {
						"title": "拜入门派",
						"description": "寻找一个适合自己的门派加入。",
						"objectives": ["与门派长老对话", "完成入门测试"],
						"rewards": {
							"experience": 100,
							"items": ["basic_sword", "spirit_stone"],
							"spirit_stones": 10
						}
					},
					"quest_2": {
						"title": "初学功法",
						"description": "学习第一个修炼功法。",
						"objectives": ["获得基础功法", "完成首次修炼"],
						"rewards": {
							"experience": 150,
							"techniques": ["basic_cultivation"],
							"spirit_stones": 20
						}
					}
				}
			},
			"chapter_2": {
				"title": "历练成长",
				"description": "通过各种历练提升自己的修为。",
				"quests": {
					"quest_1": {
						"title": "除妖任务",
						"description": "消灭威胁村民的妖兽。",
						"objectives": ["调查妖兽踪迹", "击败妖兽"],
						"rewards": {
							"experience": 300,
							"items": ["spirit_herb_common"],
							"spirit_stones": 50
						}
					}
				}
			}
		},
		"random_events": {
			"event_1": {
				"title": "奇遇",
				"description": "在探索过程中发现了一处秘境。",
				"choices": [
					{
						"text": "进入探索",
						"outcome": "获得宝物",
						"rewards": {
							"items": ["spirit_stone"],
							"spirit_stones": 30
						}
					},
					{
						"text": "谨慎离开",
						"outcome": "保全安全",
						"rewards": {
							"experience": 50
						}
					}
				]
			}
		}
	}

# 获取物品数据
func get_item_data(item_id: String) -> Dictionary:
	if not items_data.has(item_id):
		return {}
	return items_data[item_id]

# 获取功法数据
func get_technique_data(technique_id: String) -> Dictionary:
	if not techniques_data.has(technique_id):
		return {}
	return techniques_data[technique_id]
